import { Controller } from 'egg';
import { RESULT_CODE } from '../utils/constants/code';
import { saveImg } from '../utils/common/dealImg';

export default class UserController extends Controller {
  /**
   * POST /api/user/profile
   * 修改当前用户姓名、头像（URL）
   * body: { name?: string, avatar?: string }
   * 需要鉴权：从 ctx.state.user.user_id 获取用户ID
   */
  public async updateProfile() {
    const { ctx } = this;
    const userId = ctx.state?.user?.user_id;
    const { user_name } = ctx.request.body || {};
    // 参数验证
    const rule = {
      user_name: { type: 'string', required: true, message: '用户名不能为空'},
    };
    ctx.validate(rule, ctx.request.body);

    try {
      const file = ctx.request.files[0];
      const date = Date.now(); // 毫秒数
      let avatar = '';
      if (file) {
        avatar = await saveImg({
          file: file,
          targetPath: this.config.uploadPathMap.uploadAvatarDir,
          ctx,
          fileName: date,
          isAutoClear: true,
        })
      }
      const data = await ctx.service.user.updateProfile(userId, { user_name, avatar: avatar || '' });
      ctx.body = { code: RESULT_CODE.SUCCESS, data };
    } catch (err) {
      const message = (err as Error)?.message || '更新失败';
      ctx.body = { code: RESULT_CODE.FAIL, message };
    }
  }
}